// working for userLogic

// 引入数据库
const db = require('../utils/db');
// 引入加密模块
const myMd5 = require('../utils/md5password');

// 根据用户id查询用户信息
async function getUserById(id) {
    const sql = 'SELECT * FROM t_users WHERE userid = ?';
    const params = [id];
    const result = await db.query(sql, params);
    return result[0];
}

// 判断用户账号是否存在
async function checkUserAccount(account) {
    const sql = 'SELECT * FROM t_users WHERE account = ?';
    const params = [account];
    const result = await db.query(sql, params);
    return result.length > 0;
}

// 验证密码
async function checkUserPassword(account, password) {
    const sql = 'SELECT * FROM t_users WHERE account = ?';
    const params = [account, password];
    const result = await db.query(sql, params);
    let psd = myMd5.md5(password);
    if (result[0].password === psd) {
        return result[0];
    }
}

// 判断用户名是否存在
async function checkUsername(username) {
    const sql = 'SELECT * FROM t_users WHERE username = ?';
    const params = [username];
    const result = await db.query(sql, params);
    return result.length > 0;
}

// 注册用户
async function registerUser(account, password) {
    let psd = myMd5.md5(password); // 密码加密
    const sql = 'INSERT INTO t_users (account, password) VALUES (?, ?)';
    const params = [account, psd];
    const result = await db.query(sql, params);
    return result.affectedRows > 0;
}

// 创建角色
async function createRole(account, sex, username) {
    const sql = 'UPDATE t_users SET sex = ?, username = ? WHERE account = ?'
    const params = [sex, username, account];
    const result = await db.query(sql, params);
    return result.affectedRows > 0;
}

// 获取建筑物信息
async function getBuildingInfo() {
    const sql = 'SELECT * FROM t_builds';
    const result = await db.query(sql);
    return result;
}

module.exports = {
    getUserById, // 导出getUserById函数
    checkUserAccount, // 导出checkUsername函数
    registerUser, // 导出registerUser函数
    checkUsername, // 导出checkUsername函数
    createRole, // 导出createRole函数
    checkUserPassword, // 导出checkUserPassword函数
    getBuildingInfo, // 导出getBuildingInfo函数
}